package domain;

import java.sql.SQLException;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import util.DAOException;

public abstract class AbstractDAO extends HibernateDaoSupport {

	/**
	 * Spring integration
	 */
	@SuppressWarnings("unused")
	private HibernateTemplate hibernateTemplate;
	
	/**
	 * Spring integration
	 * @param sessionFactory
	 */
	public void setHibernateTemplate(SessionFactory sessionFactory) {
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
	}

	protected Long getVersionDB(final Class<?> clazz, final Integer id) throws DAOException {
		try {
			return (Long) getHibernateTemplate().execute(new HibernateCallback() {
		        
		        public Long doInHibernate(Session session) throws HibernateException, SQLException {
		        	StringBuilder requestString = new StringBuilder("select version from ");
		    		requestString.append(clazz.getSimpleName());
		    		requestString.append(" ");
		    		requestString.append(clazz.getSimpleName().toLowerCase());
		    		requestString.append(" where ");
		    		requestString.append(clazz.getSimpleName().toLowerCase());
		    		requestString.append(".id = :id");

		    		Query request = session.createQuery(requestString.toString());
		    		request.setInteger("id", id);
		    		Object version = request.uniqueResult();
		    		if (version instanceof Long)
		    			return (Long) version;
		    		throw new HibernateException("Impossible to get the version number. Class ; " + clazz.getSimpleName() + ", id : " + id + ".");
		        }
		    });
		} catch (DataAccessException e) {
			e.printStackTrace();
			throw new DAOException("Impossible to get the version. class : " + clazz.getSimpleName() + ", id : " + id);
		}
	}
}
